package protocol

import (
	"encoding/binary"
	"encoding/json"
	"fmt"
	"strings"
)

type ComponentStatus struct {
	SystemType    byte
	SystemAddress byte
	ComponentType byte
	ComponentAddr uint32
	Status        uint16
	Description   string
}

// StatusDescription 解码部件状态描述
func StatusDescription(status uint16) string {
	switch status {
	case 0x0000:
		return "测试状态"
	case 0x0001:
		return "正常运行状态"
	case 0x0002:
		return "传感器故障"
	case 0x0003:
		return "传感器故障恢复"
	// 添加其他状态的描述
	default:
		return "未知状态"
	}
}
func ParseComponentStatus(data []byte) (*ComponentStatus, error) {
	if len(data) < 40 { // 检查数据长度是否足够
		return nil, fmt.Errorf("data too short")
	}
	cs := &ComponentStatus{
		SystemType:    data[0],
		SystemAddress: data[1],
		ComponentType: data[2],
		ComponentAddr: binary.LittleEndian.Uint32(data[3:7]),
		Status:        binary.LittleEndian.Uint16(data[7:9]),
		Description:   strings.TrimRight(string(data[9:40]), "\x00"), // 去除空字符
	}
	return cs, nil
}

func ConvertToJSON2(cs *ComponentStatus) (string, error) {
	cs.Description = StatusDescription(cs.Status) + " - " + cs.Description
	jsonData, err := json.Marshal(cs)
	if err != nil {
		return "", err
	}
	return string(jsonData), nil
}

func IOSMain() {
	// 示例数据，应从TCP数据流中获取
	exampleData := []byte{0x80, 0x00, 0x0A, 0x05, 0x00, 0x00, 0x00, 0x0D, 0x00, 0xFA, 0x00 /* ... 其余部分 */}

	cs, err := ParseComponentStatus(exampleData)
	if err != nil {
		fmt.Println("Error parsing data:", err)
		return
	}

	jsonOutput, err := ConvertToJSON2(cs)
	if err != nil {
		fmt.Println("Error converting to JSON:", err)
		return
	}

	fmt.Println(jsonOutput)
}
